package com.woniu.darryringmall.admin.shiro;

import com.woniu.darryringmall.admin.entity.Manager;
import com.woniu.darryringmall.admin.jwt.Audience;
import com.woniu.darryringmall.admin.jwt.JwtUtil;
import com.woniu.darryringmall.admin.mapper.ManagerMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class DbRealm extends AuthorizingRealm {
    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private Audience audience;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Object o = principalCollection.getPrimaryPrincipal();
        int id;
        if (o instanceof Manager) {
            Manager manager = (Manager) o;
            log.debug("id:{}", manager.getId());
            id = manager.getId();
        } else {
            String jwt = (String) o;
            id = JwtUtil.getId(jwt, audience.getBase64Secret());
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        managerMapper.getPermsByManagerId(id).forEach(e -> {
            info.addStringPermission(e.getCode());
        });
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        Manager manager = managerMapper.getByAccount(t.getUsername());
        if (manager == null) {
            throw new UnknownAccountException("账号不存在！");
        }
        //设置盐值
        ByteSource salt = ByteSource.Util.bytes(manager.getAccount());
        return new SimpleAuthenticationInfo(manager, manager.getPassword(), salt, getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}